
package JET.geom;

import JET.physics.PhysicsHelper;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

/**
 *
 * @author raos
 */
public class BezierCurve {

    private final ArrayList<Vec2d>  cPoints = new ArrayList<Vec2d>();
    private final ArrayList<Vec2d>  built = new ArrayList<Vec2d>();
    private final ArrayList<Vec2d>  prev = new ArrayList<Vec2d>();
    private final Vec2d             center = new Vec2d();
    private double                  scale = 20.;
    private int order = 200;
    
    public BezierCurve() {}

    public BezierCurve(Collection<Vec2d> cPoints) {
        setCPoints(cPoints);
    }

    public void setCPoints(Collection<Vec2d> vecs) {
        this.cPoints.clear();
        center.become(PhysicsHelper.getGeomCenterOfVecs(vecs));

        int i = 0;
        for(Vec2d v : vecs) {
            Vec2d sv = new Vec2d(v);
            if (i>0 && i<vecs.size()-1) {
                sv.sub(center);
                sv.scale(this.scale);
                sv.add(center);
            }
            this.cPoints.add(sv);
            i++;
        }
    }

    public void setOrder(int n) {
        this.order = n;
    }

    public void build() {
        int o = order;

        prev.clear();
        prev.addAll(cPoints);

        while (o-->0)
        {
            built.clear();
            built.add(prev.get(0));

            for(int i=0; i<prev.size()-1; i++)
            {
                Vec2d a = prev.get(i),
                      b = prev.get(i+1);

                Vec2d v = b.getSubbed(a);
                v.scale(.5);
                v.add(a);
                built.add(v);
            }

            built.add(prev.get(prev.size()-1));
            
            // Switch
            prev.clear();
            prev.addAll(built);
        }
    }

    public Collection<Vec2d> getPointsSync() {
        return Collections.synchronizedList(prev);
    }
}

